angular.module('furion.core.run', [])

.run ($rootScope, $timeout, $ionicViewSwitcher, $ionicPlatform, $ionicHistory, $ionicLoading, $state, LimitStates, ModalManager, Toast, GestureService, TouchidService, Config, TouchAndGestureService, WechatJS) ->
  $rootScope.$on 'loading:show', (e, text)->
    $ionicLoading.hide()
    text ||= ''
    $ionicLoading.show({template: "<ion-spinner /><br />#{text}"})

  $rootScope.$on 'loading:hide', ->
    $ionicLoading.hide()

  $rootScope.goback_scope = null

  $rootScope._wechat_disable_default_share = false
  $rootScope._wechat_share_title = ->
    '@球友'
  $rootScope._wechat_share_desc = ->
    ''
  $rootScope._wechat_share_link = ->
    undefined
  $rootScope._wechat_share_img_url = ->
    undefined

  $rootScope.$on '$ionicView.enter', (event, params)->
    $rootScope.goback_scope = event.targetScope

    scope = event.targetScope
    unless scope._wechat_disable_default_share
      WechatJS.share scope._wechat_share_title(), scope._wechat_share_desc(), scope._wechat_share_link(), scope._wechat_share_img_url()

  $rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams)->
    # 检查是否需要登陆才能访问
    if -1 != LimitStates.signin.indexOf(toState.name) && !furion.storage.isLogin()
      console.debug "跳转到 #{toState.name} 需要登陆"
      $rootScope.$emit("modals:open", {modal_name: 'signin', params: {state: toState.name, params: toParams}})
      event.preventDefault()
      return

    # 检查是否需要认证后才能访问
    if -1 != LimitStates.auth.indexOf(toState.name)
      account = furion.storage.account()
      result = furion.utils.checkCardCertify(account)
      if !result.result
        Toast.show result.msg
        $state.go result.state, result.params
        event.preventDefault()
        return

    if toState.name.indexOf('app.') == -1 && toState.name.indexOf('welcome') == -1
      $ionicViewSwitcher.nextDirection 'forward'

  $rootScope.goBack = (use_origin = false)->
    return if ModalManager.closeLastModal()

    unless use_origin
      scope = $rootScope.goback_scope
      if scope && scope.goBack && scope.goBack != $rootScope.goBack
        return scope.goBack()

    if $ionicHistory.backView()
      $ionicHistory.goBack()
      console.debug '$ionicHistory.goBack'
    else
      $state.go 'app.home'
      console.debug 'app.home'
    $ionicViewSwitcher.nextDirection 'back'

  $ionicPlatform.registerBackButtonAction(
    (e)->
      # 如果在加载数据，禁止回退
      return false if $rootScope.load_status == null

      state_name = $state.current.name
      if state_name.match(/^app/) && $('.modal').length == 0 # 如果已经在tab页，按回退就直接退出app
        # 不退出，直接hide到后台
        navigator.home.home(()->
          console.debug 'success'
        , ()->
          console.debug 'fail'
        )
        e.preventDefault()
      else
        unless state_name.match(/^gesture-login/)
          # scope = angular.element($('body')).scope()
          # scope.goBack() if scope

          if $('.modal').length > 0
            ar = $('.modal')
            ar = ar[ar.length - 1]
            scope = angular.element(ar).scope()
          else
            scope = angular.element($('body')).scope()
          scope.goBack() if scope
      return false
  , 201)

  pauseApp = ()->
    url = window.location.href
    current_url = url[url.indexOf('#')..url.length-1]
    if "#/gesture-login" != current_url
      now = (new Date()).getTime()
      window.localStorage.setItem('rt-gesture_prev_lock_ts', now)

  checkResume = () ->
    TouchAndGestureService.check()

  $ionicPlatform.ready ->
    # Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    # for form inputs)
    if window.cordova and window.cordova.plugins and window.cordova.plugins.Keyboard
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar false
      cordova.plugins.Keyboard.disableScroll true

    if window.StatusBar
      StatusBar.show()
      StatusBar.styleLightContent()

    # 唤回app的事件
    document.addEventListener("resume", () ->
      checkResume()
    , false)

    # app pause的事件
    document.addEventListener("pause", () ->
      pauseApp()
    , false)

    # push
    window.furionPush.jpush.init(Config.debugMode)

    # 因为指纹设备是否支持是异步，所以要等待回调之后才进入App
    TouchidService.checkDeviceSupport ()->
      url = window.location.href
      current_url = url[url.indexOf('#')..url.length-1]
      if current_url.length <= 1 # 如果是根地址
        $state.transitionTo('welcome')

    return #   $ionicPlatform.ready ->
  return # .run(($ionicPlatform) ->
